package com.lepu.app.fun.tool.ymsjb;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.ui.wheel.ArrayWheelAdapter;
import com.core.lib.ui.wheel.NumericWheelAdapter;
import com.core.lib.ui.wheel.WheelView;
import com.core.lib.utils.DateType;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.tool.ymsjb.bean.BeanToolYiMiao;
import com.lepu.app.fun.tool.ymsjb.remind.Alarm;
import com.lepu.app.fun.tool.ymsjb.remind.AlarmTipsManager;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;

@SuppressLint("InflateParams")
public class YiMiaoAddActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener,OnTopbarNewRightButtonListener,AsyncRequest {
	private String REQUEST_DATA = "request_data";
	
	private TextView mDateEdit;
	private TextView mRemindEdit;
	private TextView mRemindYes;
	private TextView mRemindNo;
	
	public String [] mDateArray = null;
	public int mCurrentItem = 1;
	public String mTime = "";
	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tool_yimiao_add_activity);

		UtilityBase.setStatusBarRes(this, R.color.color_daichan, true);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		startActivity(new Intent(this, YiMiaoShowActivity.class),true);
	}
	
	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("疫苗时间表");
		topbar.setRightText("查看");
		topbar.setTopbarBackground(R.color.color_daichan);
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setOnTopbarNewRightButtonListener(this);
		
		boolean isFirst = getIntent().getBooleanExtra("isFirst", false);

		if(!BeanToolYiMiao.isExist(LoginUtil.getUserId())){
			ArrayList<BeanToolYiMiao> list = BeanToolYiMiao.getDataByUid("");
			for(int i=0; i<list.size(); i++){
				BeanToolYiMiao bean = list.get(i);
				bean.uid = LoginUtil.getUserId();
				BeanToolYiMiao.insert(bean);
			}
		}
		
		mDateArray = getResources().getStringArray(R.array.array_yimiao_date);
		
		mDateEdit = (TextView) findViewById(R.id.dateEditText);
		mRemindEdit = (TextView) findViewById(R.id.remindEditText);
		mRemindYes = (TextView) findViewById(R.id.yesText);
		mRemindNo = (TextView) findViewById(R.id.noText);

		mDateEdit.setOnClickListener(onClick);
		mRemindEdit.setOnClickListener(onClick);
		mRemindYes.setOnClickListener(onClick);
		mRemindNo.setOnClickListener(onClick);
		
		if(isFirst){
			mDateEdit.setText(DateUtil.stringFromDate(new Date(), DateUtil.YEAR_MONTH_DAY));
			
			//回显提醒时间
			mCurrentItem = 1;
			String remindText = mDateArray[mCurrentItem];
			mTime = "08:00";
			remindText = remindText+" "+mTime;
			
			mRemindEdit.setText(remindText);
			
			mRemindYes.setSelected(true);
		}else{
			//回显出生日期
			String babyDate = UserConfig.getConfigString(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_BABY_DATE, DateUtil.stringFromDate(new Date(), DateUtil.YEAR_MONTH_DAY));
			if(!TextUtils.isEmpty(babyDate)){
				mDateEdit.setText(babyDate);
			}
			
			//回显提醒时间
			String remindText = "";
			mCurrentItem = UserConfig.getConfigInt(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_REMIND_AN, 1);
			remindText = mDateArray[mCurrentItem];
			
			mTime = UserConfig.getConfigString(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_REMIND_TIME, "08:00");
			remindText = remindText+" "+mTime;
			
			mRemindEdit.setText(remindText);
			
			//回显提醒开关
			boolean remind = UserConfig.getConfigBoolean(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_REMIND_IS, true);
			if(remind){
				mRemindYes.setSelected(true);
				mRemindNo.setSelected(false);
				
				mRemindEdit.setClickable(true);
				mRemindEdit.setTextColor(getResources().getColor(R.color.color_text_black));
			}else{
				mRemindYes.setSelected(false);
				mRemindNo.setSelected(true);
				
				mRemindEdit.setClickable(false);
				mRemindEdit.setTextColor(getResources().getColor(R.color.color_text_black3));
			}
		}
		
	}

	@SuppressLint("DefaultLocale")
	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.testButton:
			String date = mDateEdit.getText().toString().trim();
			String remindDate = mRemindEdit.getText().toString().trim();
			boolean isRemind = false;

			if (TextUtils.isEmpty(date)) {
				UIHelper.showToast(this, "请选择宝宝出生时间");
				return;
			}
			
			if (TextUtils.isEmpty(remindDate) && mRemindYes.isSelected()) {
				UIHelper.showToast(this, "请选择提醒时间");
				return;
			}
			
			//保存提醒标志 and 设置闹钟
			if(mRemindYes.isSelected()){
				isRemind = true;
				//取消之前的alarm  重新定义
				ArrayList<Alarm> alarmList = AlarmTipsManager.getAlarmByUid(LoginUtil.getUserId());
				
				for (Alarm alarm : alarmList) {
		                Alarm.closeRemind(MyApplication.alarmManager, this, alarm.alarmId);
		                AlarmTipsManager.deleteItem(alarm.alarmId); 
		            }
				
				//保存标志
				UserConfig.setConfig(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_REMIND_IS, true);
				UserConfig.setConfig(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_REMIND_AN, mCurrentItem);
				UserConfig.setConfig(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_REMIND_TIME, mTime);
				
				//设置闹钟
				ArrayList<BeanToolYiMiao> yimiaoList = BeanToolYiMiao.getDataByUid(LoginUtil.getUserId());
				for(int i=0; i<yimiaoList.size(); i++){
					BeanToolYiMiao item = yimiaoList.get(i);
					
					Alarm alarm = new Alarm();
					
					long alarmTime = DateUtil.getLongTimeAll(date +" "+mTime);
					if(mCurrentItem == 0){  //当天
						alarmTime = alarmTime  + (Integer.valueOf(item.time)*DateUtil.MONTH_MILLIS);
					}else if(mCurrentItem == 1){  //前一天
						alarmTime = alarmTime - DateUtil.DAY_MILLIS + (Integer.valueOf(item.time)*DateUtil.MONTH_MILLIS);
					}else if(mCurrentItem == 2){  //前三天
						alarmTime = alarmTime - (DateUtil.DAY_MILLIS * 3) + (Integer.valueOf(item.time)*DateUtil.MONTH_MILLIS);
					}
					
					alarm.uid = LoginUtil.getUserId();
					alarm.alarmTime = alarmTime;
					alarm.setTime = DateUtil.getNowTimeInMillis();
					alarm.showTime = remindDate;
					alarm.note = "宝宝要打疫苗了,注意哦!";
					
					if(i > 0 && !item.time.equals(yimiaoList.get(i-1))){
						Alarm.setRemind(alarm, MyApplication.alarmManager, YiMiaoAddActivity.this);
					}
					
				}
			}
			
			//保存提醒标志  and 取消闹钟
			if(mRemindNo.isSelected()){
				isRemind = false;
				UserConfig.setConfig(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_REMIND_IS, false);
				
				//关掉所有闹钟
				ArrayList<Alarm> alarmList = AlarmTipsManager.getAlarmByUid(LoginUtil.getUserId());
				for(int i=0; i<alarmList.size(); i++){
					Alarm.closeRemind(MyApplication.alarmManager, YiMiaoAddActivity.this, alarmList.get(i).alarmId);
				}
			}
			
			//判断是否跳到主页
			String baby = UserConfig.getConfigString(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_BABY_DATE, "");
			
			if(TextUtils.isEmpty(baby)){
				startActivity(new Intent(YiMiaoAddActivity.this,YiMiaoActivity.class), true);
			}
			
			UserConfig.setConfig(YiMiaoAddActivity.this, Const.CONFIG_YIMIAO_BABY_DATE, date);
			
			request(date, isRemind, mCurrentItem, mTime);
			showProgressDialog();
			break;

		default:
			break;
		}
	}
	
	View.OnClickListener onClick = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.dateEditText:
				showBirthDateDialog(mDateEdit);
				break;
			case R.id.remindEditText:
				if(TextUtils.isEmpty(mDateEdit.getText().toString())){
					UIHelper.showToast(YiMiaoAddActivity.this, "请先选择宝宝出生时间");
					return;
				}
				showDateTimeDialog(mRemindEdit);
				break;
			case R.id.yesText:
				mRemindYes.setSelected(true);
				mRemindNo.setSelected(false);
				
				mRemindEdit.setClickable(true);
				mRemindEdit.setTextColor(getResources().getColor(R.color.color_text_black));
				break;
			case R.id.noText:
				mRemindYes.setSelected(false);
				mRemindNo.setSelected(true);
				
				mRemindEdit.setClickable(false);
				mRemindEdit.setTextColor(getResources().getColor(R.color.color_text_black3));
				break;
			default:
				break;
			}
		}
	};
	
	//上传
	public void request(String babyDate, boolean isRemind, int remindAn, String remindTime ) {
		int remind = 0;

		if(isRemind){
			remind = 1;
		}else{
			remind = 0;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("ToolID", 2);
			params.put("BabyBirthday", babyDate);
			params.put("IsAlert", remind);
			params.put("AlertBeforeDay", remindAn);
			params.put("AlertTime", remindTime);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.getUploadYiMiaoUrl(), map, null, this,REQUEST_DATA, true, false);
	}

	private void showBirthDateDialog(final TextView textView) {
		String babyDate = UserConfig.getConfigString(YiMiaoAddActivity.this, Const.CONFIG_APP_BABY_DATE, "");
		String dateStr = "";
		if (TextUtils.isEmpty(babyDate)) {
			dateStr = DateUtilBase.stringFromDate(new Date(),DateUtilBase.YEAR_MONTH_DAY);
		} else {
			Date date = DateUtilBase.dateFromString(babyDate,DateUtilBase.YEAR_MONTH_DAY);
			dateStr = DateUtilBase.stringFromDate(date,DateUtilBase.YEAR_MONTH_DAY);
		}

		Date date = DateUtilBase.dateFromString(dateStr,DateUtilBase.YEAR_MONTH_DAY);
		MyDialog dialog = new MyDialog(YiMiaoAddActivity.this)
				.setTitle("请选择宝宝出生日期")
				.setDateTimePicker(date, DateType.YEAR_MONTH_DAY)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// 如果是个数,则显示为"02"的样式
						WheelView wv_year = (WheelView) v
								.findViewById(R.id.year);
						WheelView wv_month = (WheelView) v
								.findViewById(R.id.month);
						WheelView wv_day = (WheelView) v.findViewById(R.id.day);

						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String text = (wv_year.getCurrentItem() + MyDialog.START_YEAR)
								+ "-"
								+ decimal.format((wv_month.getCurrentItem() + 1))
								+ "-"
								+ decimal.format((wv_day.getCurrentItem() + 1));

						if(DateUtil.getLongTime(text) > DateUtil.getLongTime(DateUtil.stringFromDate(new Date(), DateUtilBase.YEAR_MONTH_DAY))){
							UIHelper.showToast(YiMiaoAddActivity.this, "不能选择未来时间");
						}else{
							textView.setText(text);
						}
						
					}
				});

		dialog.create(null).show();
	}
	
	private void showDateTimeDialog(final TextView textView) {
		View view = LayoutInflater.from(YiMiaoAddActivity.this).inflate(R.layout.tool_yimiao_date_view, null);
		
		//------ string wheel
		final WheelView wv_content = (WheelView) view.findViewById(R.id.custom);
		wv_content.setAdapter(new ArrayWheelAdapter<String>(mDateArray));
		wv_content.setCurrentItem(1);
		
        //------ 时：分
		int hour = 0;
		int minutes = 0;

		Calendar calendar = Calendar.getInstance();

		calendar.setTime(new Date());

		hour = calendar.get(Calendar.HOUR_OF_DAY);
		minutes = calendar.get(Calendar.MINUTE);

		// 时
		final WheelView wv_hour = (WheelView) view.findViewById(R.id.hour);
		wv_hour.setAdapter(new NumericWheelAdapter(0, 23));
		wv_hour.setCyclic(true);// 可循环滚动
		wv_hour.setLabel("时");// 添加文字
		wv_hour.setCurrentItem(hour);// 初始化时显示的数据

		// 分
		final WheelView wv_minutes = (WheelView) view.findViewById(R.id.minute);
		wv_minutes.setAdapter(new NumericWheelAdapter(0, 59));
		wv_minutes.setCyclic(true);
		wv_minutes.setLabel("分");
		wv_minutes.setCurrentItem(minutes);

		// 根据屏幕密度来指定选择器字体的大小
		int textSize = UtilityBase.getTextNumberSize(YiMiaoAddActivity.this);

		wv_content.TEXT_SIZE = textSize;
		wv_hour.TEXT_SIZE = textSize;
		wv_minutes.TEXT_SIZE = textSize;
		
		MyDialog dialog = new MyDialog(YiMiaoAddActivity.this)
				.setTitle("请选择时间")
				.addView(view)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						mCurrentItem = wv_content.getCurrentItem();
						
						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String text = mDateArray[mCurrentItem]
								+" "
								+decimal.format((wv_hour.getCurrentItem() ))
								+ ":"
								+decimal.format((wv_minutes.getCurrentItem() ));

						textView.setText(text);

						mTime = decimal.format((wv_hour.getCurrentItem() ))
								+ ":"
								+decimal.format((wv_minutes.getCurrentItem() ));
					}
				});

		dialog.create(null).show();
	}

	@Override
	public void RequestComplete(Object arg0, Object arg1) {
		hideProgressDialog();
		finish(true);
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		hideProgressDialog();
		finish(true);
	}
	
}
